package com.everydayflash.cart.points3d {
	import com.everydayflash.cart.core.AbstractSketch;
	import com.everydayflash.cart.core.Pixel3D;
	
	import flash.display.BitmapData;
	import flash.events.MouseEvent;
	import flash.filters.BlurFilter;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix3D;
	import flash.geom.PerspectiveProjection;
	import flash.geom.Point;
	import flash.geom.Vector3D;		

	/**
	 * @author bartekd
	 */
	public class Points3D2 extends AbstractSketch {
		
		private var pts:Vector.<Pixel3D>;
	
		private var projection:Matrix3D;
		private var angleX:Number = 0;		private var angleY:Number = 0;
		private var matrix:Matrix3D;
		
		[Embed (source="pattern.png")]
		private var Pattern:Class;
		private var pattern:BitmapData;

		
		override protected function init():void {
			var p:PerspectiveProjection = new PerspectiveProjection();
			p.focalLength = 400;
			projection = p.toMatrix3D();
			matrix = new Matrix3D();
	
			pts = new Vector.<Pixel3D>();
			pattern = new Pattern().bitmapData;
			
			var rd:Number = 200;
			for (var i:int = 0; i < 2500; i++) {
				var r:Pixel3D = new Pixel3D(rdpos, rdpos, rdpos);
				r.color = pattern.getPixel(i % 50, i / 50);
				r.normalize();
				r.x *= rd;				r.y *= rd;				r.z *= rd;
				pts.push(r);
			}
			
			
		}
		
		override protected function mouseDown(e:MouseEvent):void {
			var rd:Number = 150 * Math.random();
			
			for (var i:int = 0; i < 2500; i++) {
				var r:Pixel3D = pts[i];
				r.normalize();
				r.x *= rd;
				r.y *= rd;
				r.z *= rd;
			}
		}
		
		private function get rdpos():Number {
			return 1 - (Math.random() * 2);
		}
		
		override protected function draw():void {
//			clearBCanvas();
			bcanvas.applyFilter(bcanvas, bcanvas.rect, new Point(), new BlurFilter(4,4,1));
			bcanvas.colorTransform(bcanvas.rect, new ColorTransform(1,1,1,.8));

			angleX -= (mouseX - sw/2) / sw/2 * 10;			angleY += (mouseY - sh/2) / sh/2 * 10;

			

			for (var i:int = 0;i < pts.length; i++) {
				matrix.identity();
				matrix.appendRotation(angleX, new Vector3D(0, 0, 1));
				matrix.appendRotation(angleY, new Vector3D(1, 0, 0));
				matrix.appendTranslation(0, 0, 350);
			
				var v:Pixel3D = pts[i];
				
				var iv:Vector3D = matrix.transformVector(v);
				
				var vz:Number = 1 - (iv.z / 500);
				vz = Math.min(1, vz);
				vz = Math.max(0, vz);
				
				iv = projection.transformVector(iv);
				iv.project();

				var c:uint = (vz * 255) << 24 | v.color;
				
				drawParticle(sw / 2 + iv.x, sh/2 + iv.y, c);
			}
		}
		
		private function drawParticle(x:Number, y:Number, c:uint):void {
			bcanvas.setPixel32(x, y, c);			bcanvas.setPixel32(x-1, y, c);			bcanvas.setPixel32(x, y-1, c);			bcanvas.setPixel32(x+1, y, c);			bcanvas.setPixel32(x, y+1, c);
		}
	}
}
